// import _ from "lodash";


/**
 * @description: null判断
 * @param {*} val
 * @return {*}
 */
function validatenull(val) {
  if (
    val instanceof Date ||
    typeof val === "boolean" ||
    typeof val === "number" ||
    val instanceof Array
  )
    return false;
  else if (val instanceof Function) {
    const fun = val.toString().replace(/\s+/g, "");
    const arr = ["({value})=>{}", "(res,cb)=>{}", "(res)=>{}", "()=>{}"];
    if (arr.includes(fun)) return true;
    else return false;
  } else if (val instanceof Object) {
    for (var o in val) {
      return false;
    }
    return true;
  } else {
    if (
      val === "null" ||
      val == null ||
      val === "undefined" ||
      val === undefined ||
      val === ""
    ) {
      return true;
    }
    return false;
  }
}


/**
 * @description: 返回满足条件的Column
 * @param {*} receiverProp
 * @param {*} option
 * @return {*}
 */
function getColumnByProp(receiverProp, option) {
  // return _.find(option.column, { prop: receiverProp });
  return option.column.find(({prop}) => prop === receiverProp)
}

/**
 * @description: 数据模型配置的相关请求
 * @param {*} tableId
 * @param {*} query
 * @return {*}
 */
async function getTableData(tableId, query) {
  let searchList = [];
  if (query && query.searchKey) searchList.push(query);
  // let res = await request.bmo.getFormTableDbData(tableId, {
  //   searchList: searchList,
  // });
  return res;
}


/**
 * @description: 默认导出项，处理拖拉拽表单配置option为avue-form数据格式
 * @description: 递归处理，
 * @param {*} option
 * @param {*} formData
 * @return {*}
 */
export async function generateInitialize(option, formData) {
  for (let index = 0; index < option?.group?.length; index++) {
    let g = option.group[index];
    await generateInitialize(g, formData);
  }

  for (let index = 0; index < option?.column?.length; index++) {
    let c = option.column[index];
    if (c.type === "dynamic" && c.children) {
      await generateInitialize(c.children, formData);
    }

    //doSome
    await _generateInitialize(c);

    if (c.type === "customCrud") {
      c.params = {
        ...c.params,
        formData: formData,
      };
    }
  }

  generateControlEvent(option);
}

/**
 * @description: 获取数据模型列表，配置数据模型
 * @param {*} c
 * @return {*}
 */
async function _generateInitialize(c) {
  if (!validatenull(c?.dicTableId)) {
    try {
      let response = await getTableData(c.dicTableId, c.dicTableQuery);
      c.dicData = response.data;
    } catch (err) {
      console.error(`初始化数据表失败:${c.dicTableId} ${c.dicTableQuery}`, err);
    }
  }
}


/**
 * @description: 从this全局对象中获取Avue组件配置
 * @param {*} vueComponent
 * @return {*}
 */
function findAvue(vueComponent) {
  if (vueComponent?.$vnode.tag.endsWith("avue-form")) {
    return vueComponent;
  }
  if (vueComponent?.$parent) {
    return findAvue(vueComponent.$parent);
  }

  return undefined;
}


/**
 * @description: 处理自定义事件，从全局变量this获取Avue相关option配置，处理事件相关绑定
 * @param {*} option
 * @return {*}
 */
export function generateControlEvent(option) {
  option.column?.forEach((c) => {
    if (c.eventList?.length > 0) {
      c.change = async function ({ value }) {
        let component = findAvue(this);
        if (component) {
          for (const sender of c.eventList) {
            await generateSenderEvent(
              c,
              sender,
              value,
              option,
              component,
              this
            );
          }
        }
      };
    }
  });
}

/**
 * @description: 处理事件绑定关系
 * @param {*} c
 * @param {*} sender
 * @param {*} value
 * @param {*} option
 * @param {*} component
 * @param {*} vue
 * @return {*}
 */
async function generateSenderEvent(c, sender, value, option, component, vue) {
  try {
    let column = getColumnByProp(sender.receiver.prop, option);
    if (column) {
      let data = null;

      // 处理数据源
      // 数据模型，请求配置数据
      if (sender.source.type === "tableModel") {
        let res = await getTableData(sender.source.tableModel.tableId, {
          ...sender.source.tableModel.query,
          searchVal: value,
        });
        data = res.data;
      } else if (sender.source.type === "selfDic") {
        // 表单本身配置数据字典
        let fieldData = c.dicData.find((d) => d[c.props.value] === value);
        if (fieldData) {
          data = fieldData[sender.source.selfDic.field.at(-1)];
        }
      } else if (sender.source.type === "selfValue") {
        // 表单本身的值
        data = value;
      }

      // 接收方式
      // 事件绑定直接复制到this的Avue配置上
      if (sender.receiver.type === "dic") {
        vue.$set(component.form, column.prop, undefined);
        vue.$set(column, "dicData", data);
        vue.$set(column, "props", sender.receiver.props);
      } else if (sender.receiver.type === "value") {
        vue.$set(component.form, column.prop, data);
      }
    }
  } catch (err) {
    console.error("发送事件异常", err);
  }
}

/**
 * @description: 事件添加的默认字典配置项
 * @param {*} prop
 * @param {*} label
 * @return {*}
 */
export function createEvent(prop, label) {
  return {
    receiver: {
      prop: prop, //向谁发送
      label: label,
      type: "dic", //如何接收数据 value,dic
      props: {
        label: "",
        value: "",
        desc: "",
      },
    },
    source: {
      type: "tableModel", //tableModel,selfDic,selfValue
      tableModel: {
        tableId: "",
        query: {},
      },
      selfDic: {
        field: [],
        props: {
          label: "",
          value: "",
          desc: "",
        },
      },
    },
  };
}
